/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.grant.department.impl;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.exception.PermissionException;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.grant.department.RbacGrantDepartmentPcFuncPermmisionService;
import com.je.rbac.service.permission.GrantMethodEnum;
import com.je.rbac.service.permission.GrantTypeEnum;
import com.je.rbac.service.permission.PermissionOperationTypeEnum;
import com.je.rbac.service.permission.PermissionTypeEnum;
import com.je.rbac.service.permission.template.PcFuncBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RbacGrantDepartmentPcFuncPermmisionServiceImpl implements RbacGrantDepartmentPcFuncPermmisionService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private PcFuncBaseService pcFuncBaseService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private RbacDepartmentService rbacDepartmentService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveDeptFuncShowPermission(String deptId, String funcCode, String excludeChecked, GrantTypeEnum grantType) {
        if (!Strings.isNullOrEmpty(excludeChecked)) {
            if ("0".equals(excludeChecked) || "false".equals(excludeChecked)) {
                excludeChecked = "1";
            } else {
                excludeChecked = "0";
            }
        }
        //写入基础权限
        DynaBean funcBasePermBean = pcFuncBaseService.writePcFuncShowPermission(funcCode, true);

        Set<String> extendDepartmentIdList = rbacDepartmentService.findExtendIds(Lists.newArrayList(deptId));
        extendDepartmentIdList.add(deptId);
        List<DynaBean> associationList = metaService.select("JE_RBAC_DEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .in("JE_RBAC_DEPARTMENT_ID", extendDepartmentIdList)
                .eq("JE_RBAC_PERM_ID", funcBasePermBean.getStr("JE_RBAC_PERM_ID")));
        Map<String,String> havedRolePermissionMap = new HashMap<>();
        for (DynaBean eachAssociationBean : associationList) {
            havedRolePermissionMap.put(eachAssociationBean.getStr("JE_RBAC_PERM_ID"),eachAssociationBean.getStr("DEPTPERM_EXCLUDE_CODE"));
        }

        //写入关联关系
        if (havedRolePermissionMap.containsKey(funcBasePermBean.getStr("JE_RBAC_PERM_ID"))) {
            if (!Strings.isNullOrEmpty(excludeChecked) && "1".equals(havedRolePermissionMap.get(funcBasePermBean.getStr("JE_RBAC_PERM_ID")))) {
                metaService.executeSql("UPDATE JE_RBAC_DEPTPERM SET DEPTPERM_NOT_CHECKED = {0} WHERE JE_RBAC_DEPARTMENT_ID={1} AND JE_RBAC_PERM_ID={2}",
                        excludeChecked,
                        deptId,
                        funcBasePermBean.getStr("JE_RBAC_PERM_ID"));
            }
            return;
        }
        DynaBean rolePermBean = new DynaBean("JE_RBAC_DEPTPERM", false);
        rolePermBean.set("JE_RBAC_DEPARTMENT_ID", deptId);
        rolePermBean.set("JE_RBAC_PERM_ID", funcBasePermBean.getStr("JE_RBAC_PERM_ID"));
        rolePermBean.set("DEPTPERM_EXCLUDE_CODE", "0");
        rolePermBean.set("DEPTPERM_EXCLUDE_NAME", "否");
        //授权方式
        rolePermBean.set("DEPTPERM_TYPE_CODE", GrantMethodEnum.DEPARTMENT.name());
        rolePermBean.set("DEPTPERM_TYPE_NAME", GrantMethodEnum.DEPARTMENT.getDesc());
        //授权类型
        rolePermBean.set("DEPTPERM_GRANTTYPE_CODE", grantType.name());
        rolePermBean.set("DEPTPERM_GRANTTYPE_NAME", grantType.getDesc());
        //todo 设置租户信息

        commonService.buildModelCreateInfo(rolePermBean);
        metaService.insert(rolePermBean);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void removeDeptFuncPermission(String deptId, String funcCode, GrantTypeEnum grantType, boolean update, boolean delete) {
        List<DynaBean> permissionBaseBeanList = pcFuncBaseService.findPcFuncBasePermission(funcCode, update, delete,false);
        List<String> permIdList = new ArrayList<>();
        for (DynaBean eachBean : permissionBaseBeanList) {
            permIdList.add(eachBean.getStr("JE_RBAC_PERM_ID"));
        }
        metaService.delete("JE_RBAC_DEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .eq("JE_RBAC_DEPARTMENT_ID", deptId)
                .in("JE_RBAC_PERM_ID", permIdList));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public List<DynaBean> findDeptFuncPermission(String deptId, String funcCode, GrantTypeEnum grantType, boolean update, boolean delete) {
        List<String> operatorList = Lists.newArrayList(PermissionOperationTypeEnum.SHOW.getCode());
        if (update) {
            operatorList.add(PermissionOperationTypeEnum.UPDATE.getCode());
        }
        if (delete) {
            operatorList.add(PermissionOperationTypeEnum.DELETE.getCode());
        }
        return metaService.select("JE_RBAC_VDEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .eq("JE_RBAC_DEPARTMENT_ID", deptId)
                .eq("PERM_OBJECT", funcCode)
                .in("PERM_TYPE_CODE", Lists.newArrayList(
                        PermissionTypeEnum.FUNC_PC_BASE.name(),
                        PermissionTypeEnum.BUTTON_PC.name()
                )).in("PERM_OPERATE_CODE", operatorList));
    }

    @Override
    public List<DynaBean> findExtendedDeptFuncPermission(String deptId, String funcCode, GrantTypeEnum grantType, boolean update, boolean delete) throws PermissionException {
        List<String> operatorList = Lists.newArrayList(PermissionOperationTypeEnum.SHOW.getCode());
        if (update) {
            operatorList.add(PermissionOperationTypeEnum.UPDATE.getCode());
        }
        if (delete) {
            operatorList.add(PermissionOperationTypeEnum.DELETE.getCode());
        }
        DynaBean deptBean = metaService.selectOne("JE_RBAC_DEPARTMENT", ConditionsWrapper.builder().eq("JE_RBAC_DEPARTMENT_ID", deptId));
        if (deptBean == null) {
            throw new PermissionException("Can't find the role!");
        }
        String path = deptBean.getStr("SY_PATH");
        if (Strings.isNullOrEmpty(path)) {
            throw new PermissionException("Can't find the role path!");
        }

        List<String> deptIdList = Splitter.on("/").splitToList(path);
        return metaService.select("JE_RBAC_VDEPTPERM", ConditionsWrapper.builder()
                .eq("DEPTPERM_GRANTTYPE_CODE", grantType.name())
                .in("JE_RBAC_DEPARTMENT_ID", deptIdList)
                .eq("PERM_OBJECT", funcCode)
                .in("PERM_TYPE_CODE", Lists.newArrayList(
                        PermissionTypeEnum.FUNC_PC_BASE.name(),
                        PermissionTypeEnum.BUTTON_PC.name()
                )).in("PERM_OPERATE_CODE", operatorList));
    }

}
